//
//  SwiftChannelPlugin.swift
//  Runner
//
//  Created by topnet on 2021/12/20.
//

import UIKit
import Flutter
import GMObjC

class SwiftChannelPlugin: NSObject {
    static let channelName = "flutter_method_channel"
    public var channel: FlutterMethodChannel
    static var instance: SwiftChannelPlugin!
    init(_ channel: FlutterMethodChannel) {
        self.channel = channel
    }
    
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: channelName, binaryMessenger: registrar.messenger())
        let instance = SwiftChannelPlugin(channel)
        self.instance = instance
        registrar.addMethodCallDelegate(instance, channel: channel)
    }
}

extension SwiftChannelPlugin: FlutterPlugin {
    func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        let args = call.arguments
        switch call.method {
            case "openNotificationSettings":
                openNotificatinSettings();
                break
            case "openLocationServiceSetting":
                openLocationServiceSetting();
                break

            default:
                result(false)
            break
        }
    }

     // openNotificationSettings
     func openNotificatinSettings() {
        if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {

            if #available(iOS 10.0, *) {

                UIApplication.shared.open(url, options: [:], completionHandler: nil)

            } else {

                // Fallback on earlier versions

            }

        }

    }

    // 打开定位服务设置
    func  openLocationServiceSetting() {
        var url : URL!
        if #available(iOS 10.0, *) {
            url = URL(string: UIApplication.openSettingsURLString)
        } else {
            url = URL(string: "prefs:root=LOCATION_SERVICES")
        }
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url)
        }

    }
}
